package com.example.myapplication

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

class RegisterActivity : AppCompatActivity() {
    
    private lateinit var editTextUsername: EditText
    private lateinit var editTextPassword: EditText
    private lateinit var editTextConfirmPassword: EditText
    private lateinit var editTextRealName: EditText
    private lateinit var spinnerDepartment: Spinner
    private lateinit var spinnerUserType: Spinner
    private lateinit var buttonRegister: Button
    private lateinit var buttonCancel: Button
    private lateinit var databaseHelper: DatabaseHelper
    private lateinit var editTextPhone: EditText // 新增手机号
    
    private val departments = listOf("内科", "外科", "儿科", "妇产科", "急诊科", "重症医学科", "其他")
    private val userTypes = listOf("普通用户", "科室管理员")
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        
        // 确保Activity可以处理软键盘
        window.setSoftInputMode(android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        
        databaseHelper = DatabaseHelper(this)
        
        initViews()
        setupSpinners()
        setupListeners()
    }
    
    private fun initViews() {
        editTextUsername = findViewById(R.id.editTextUsername)
        editTextPassword = findViewById(R.id.editTextPassword)
        editTextConfirmPassword = findViewById(R.id.editTextConfirmPassword)
        editTextRealName = findViewById(R.id.editTextRealName)
        spinnerDepartment = findViewById(R.id.spinnerDepartment)
        spinnerUserType = findViewById(R.id.spinnerUserType)
        buttonRegister = findViewById(R.id.buttonRegister)
        buttonCancel = findViewById(R.id.buttonCancel)
        // 新增
        editTextPhone = findViewById(R.id.editTextPhone)
    }
    
    private fun setupSpinners() {
        // 科室选择器
        val deptAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, departments)
        deptAdapter.setDropDownViewResource(R.layout.spinner_item)
        spinnerDepartment.adapter = deptAdapter
        // 用户类型选择器
        val typeAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, userTypes)
        typeAdapter.setDropDownViewResource(R.layout.spinner_item)
        spinnerUserType.adapter = typeAdapter
    }
    
    private fun setupListeners() {
        buttonRegister.setOnClickListener {
            registerUser()
        }
        
        buttonCancel.setOnClickListener {
            finish()
        }
    }
    
    private fun registerUser() {
        val username = editTextUsername.text.toString().trim()
        val password = editTextPassword.text.toString().trim()
        val confirmPassword = editTextConfirmPassword.text.toString().trim()
        val realName = editTextRealName.text.toString().trim()
        val department = spinnerDepartment.selectedItem.toString()
        val userTypeText = spinnerUserType.selectedItem.toString()
        val phone = editTextPhone.text.toString().trim()

        // 校验用户名
        if (username.isEmpty()) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show(); return
        }
        if (!username.matches(Regex("^[a-zA-Z0-9_]{4,20}$"))) {
            Toast.makeText(this, "用户名仅限4-20位字母、数字或下划线", Toast.LENGTH_SHORT).show(); return
        }
        // 校验密码
        if (password.isEmpty()) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show(); return
        }
        if (password.length < 6) {
            Toast.makeText(this, "密码长度至少6位", Toast.LENGTH_SHORT).show(); return
        }
        if (password != confirmPassword) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show(); return
        }
        // 校验真实姓名
        if (realName.isEmpty()) {
            Toast.makeText(this, "请输入真实姓名", Toast.LENGTH_SHORT).show(); return
        }
        // 校验科室
        if (department.isEmpty()) {
            Toast.makeText(this, "请选择科室", Toast.LENGTH_SHORT).show(); return
        }
        // 校验手机号
        if (phone.isEmpty()) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show(); return
        }
        if (!phone.matches(Regex("^1[3-9]\\d{9}$"))) {
            Toast.makeText(this, "手机号格式不正确", Toast.LENGTH_SHORT).show(); return
        }
        // 检查用户名是否已存在
        val existingUsers = databaseHelper.getAllUsers()
        if (existingUsers.any { it.username == username }) {
            Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show(); return
        }
        // 确定用户类型
        val userType = when (userTypeText) {
            "科室管理员" -> UserType.DEPARTMENT_ADMIN
            else -> UserType.USER
        }
        // 创建用户
        val user = User(
            username = username,
            password = password,
            realName = realName,
            department = department,
            userType = userType,
            isActive = true,
            isApproved = false, // 需要审批
            phone = phone
        )
        val userId = databaseHelper.addUser(user)
        if (userId > 0) {
            // 发送实时消息通知管理员
            try {
                val webSocketManager = com.example.myapplication.realtime.WebSocketManager.getInstance(this)
                webSocketManager.sendUserRegisterMessage(
                    userId = userId,
                    username = username,
                    realName = realName,
                    department = department,
                    userType = userType.name,
                    phone = phone
                )
                android.util.Log.d("RegisterActivity", "用户注册实时消息发送成功")
            } catch (e: Exception) {
                android.util.Log.e("RegisterActivity", "发送用户注册实时消息失败", e)
                // 实时消息发送失败不影响注册流程
            }
            showSuccessDialog()
        } else {
            Toast.makeText(this, "注册失败，请重试", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun showSuccessDialog() {
        AlertDialog.Builder(this)
            .setTitle("注册成功")
            .setMessage("您的账号已提交，等待管理员审批。审批通过后即可登录使用。")
            .setPositiveButton("确定") { _, _ ->
                // 注册成功后自动启动实时通信服务
                try {
                    com.example.myapplication.realtime.RealtimeService.startService(this)
                    android.util.Log.d("RegisterActivity", "实时通信服务启动成功")
                } catch (e: Exception) {
                    android.util.Log.e("RegisterActivity", "启动实时通信服务失败", e)
                }
                finish()
            }
            .setCancelable(false)
            .show()
    }
} 